
import _ from 'lodash'
import { CODE, ErrorInfo } from '../../error'
import { masterName } from '../../proxys/group'

export const edit = async (auth, req, res, next) => {
  let MasterName = await masterName()
  let { name, level, team, desc } = req.body
  let { _id } = req.params
  let options = {}
  if (auth.group.level !== 9999) {
    return res.api(null, CODE.ERROR_OPERATE_MASTER_PERMISSION, [MasterName])
  }
  if (!_id || _id.length !== 24) {
    return res.api(null, CODE.ERROR_VALID_IDMARK_NOTEXIST)
  }
  if (!name) {
    return res.api(null, CODE.ERROR_VALID_GROUPNAME_REQUIRED)
  }
  options['name'] = _.trim(name)
  if (/^[0-9]{1,4}$/.test(level) && _.toInteger(level) !== 9999) {
    options['level'] = _.toInteger(level)
  }
  if (team) {
    options['team'] = team
  }
  if (desc) {
    options['desc'] = desc
  }
  return next({
    query: { _id },
    info: options,
    auth
  })
}

export const create = async (auth, req, res, next) => {
  let MasterName = await masterName()
  let { name, level, team, desc } = req.body
  let options = {}
  if (auth.group.level !== 9999) {
    return res.api(null, CODE.ERROR_OPERATE_MASTER_PERMISSION, [MasterName])
  }
  if (!name) {
    return res.api(null, CODE.ERROR_VALID_GROUPNAME_REQUIRED)
  }
  options['name'] = _.trim(name)
  options['level'] = 0
  if (/^[0-9]{1,4}$/.test(level) && _.toInteger(level) !== 9999) {
    options['level'] = _.toInteger(level)
  }
  if (team) {
    options['team'] = team
  }
  if (desc) {
    options['desc'] = desc
  }
  return next({
    info: options,
    auth
  })
}

export const remove = (auth, req, res, next) => {
  let { _id } = req.body
  if (auth.group.level !== 9999) {
    return res.api(null, CODE.ERROR_OPERATE_MASTER_PERMISSION, [MasterName])
  }
  if (!_id || _id.length !== 24) {
    return res.api(null, CODE.ERROR_VALID_IDMARK_NOTEXIST)
  }
  return next({ _id, auth })
}

export const setFlag = (auth, req, res, next) => {
  let { _id } = req.params
  let { flag } = req.body
  if (auth.group.level !== 9999) {
    return res.api(null, CODE.ERROR_OPERATE_MASTER_PERMISSION, [MasterName])
  }
  if (!_id || _id.length !== 24) {
    return res.api(null, CODE.ERROR_VALID_IDMARK_NOTEXIST)
  }
  return next({ query: { _id }, info: { flag }, auth })
}